package tgc.edu.exam.web.controller;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.custom.CommonController;
import tgc.edu.exam.custom.DataGridUtils;
import tgc.edu.exam.custom.TablePageable;
import tgc.edu.exam.entity.Student;
import tgc.edu.exam.entity.SysFile;
import tgc.edu.exam.entity.TbClass;
import tgc.edu.exam.entity.TbCurriculum;
import tgc.edu.exam.entity.VideoCourseware;
import tgc.edu.exam.service.SysFileService;
import tgc.edu.exam.service.TbCurriculumService;
import tgc.edu.exam.service.VideoCoursewareService;
import tgc.edu.exam.web.form.SysFileForm;

@Controller
@RequestMapping(value="/coursewarev")
public class SysFileController extends CommonController<SysFile, Integer, SysFileForm> {

	@Autowired
	private SysFileService fileservice;
	@Autowired
	private TbCurriculumService tbCurriculumService;
	@Autowired
	private VideoCoursewareService videoservice;
	
	@RequestMapping(value="/video")
	public void video() {
		
	}
	@Override
	public void edit(SysFileForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		List<TbCurriculum> list = tbCurriculumService.findAll();
		map.put("data", list);
		super.edit(form, map);
	}

	@RequestMapping(value="/vedit")
	public void vedit(ModelMap map) {
		List<TbCurriculum> list = tbCurriculumService.findAll();
		map.put("data", list);
	}
	
	@RequestMapping(value="/del")
	@ResponseBody
	public String del(Integer id) {
		try {
			Specification<VideoCourseware> spec2 = buildSpec2(id);
			List<VideoCourseware> list2 = videoservice.findAll(spec2);
			for (VideoCourseware videoCourseware : list2) {
				videoservice.delete(videoCourseware);
			}
			SysFile sysflie = fileservice.findById(id);
			File file = new File("c:/jeecgs/video/"+sysflie.getUuid());
			if (file.isFile() && file.exists()) {
				file.delete();
				System.out.println("删除成功");
			}
			fileservice.deleteById(id);
			return "操作成功";
		} catch (Exception e) {
			return "操作失败";
		}
	}
	
	private Specification<VideoCourseware> buildSpec2(Integer id) {
		Specification<VideoCourseware> specification = new Specification<VideoCourseware>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<VideoCourseware> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				rules.add(cb.equal(root.get("sysfile").get("id"), id));
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
	
	/***
	 * 课件视频资源page
	 * @param pageParam
	 * @param form
	 * @return
	 */
	@RequestMapping(value="/page1")
	@ResponseBody
	public Object page1(TablePageable pageParam,SysFileForm form) {
		PageRequest pageable = pageParam.bulidPageRequest();
		Specification<SysFile> spec = buildSpec1(form);
		Page<SysFile> page=fileservice.findAll(spec, pageable);
		return DataGridUtils.buildResult(page);
	}
	
	/***
	 * 课件视频资源查询
	 * @param form
	 * @return
	 */
	private Specification<SysFile> buildSpec1(SysFileForm form) {
		Specification<SysFile> specification = new Specification<SysFile>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<SysFile> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				Predicate name = cb.like(root.get("filetypename"), "%课件视频资源%");
				rules.add(name);
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
	/***
	 * 课件视频资源保存
	 * @param form
	 * @return
	 */
	@RequestMapping(value = "/save1")
	@ResponseBody
	public Object save1(SysFileForm form) {
		try {
			SysFile sysFile = fileservice.findByUuid(form.getUuid());
			sysFile.setResourceprofile(form.getResourceprofile());
			sysFile.setTbCurriculum(tbCurriculumService.findById(form.getTbCurriculumid()));
			sysFile.setIsUsed(true);
			sysFile.setFiletypename("课件视频资源");
			fileservice.save(sysFile);
			return "数据保存成功";
		} catch (Exception e) {
			return "数据保存失败";
		}
	}

	/***
	 * 课件视频资源上传
	 * @param file
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/upload1")
	@ResponseBody
	private Object toFilesave1(MultipartFile file, ModelMap map) {
		String uuid = UUID.randomUUID().toString();
		boolean boole = fileservice.savefilevodeo(file, uuid, "");
		String filename = file.getOriginalFilename();
		StringBuffer sb = new StringBuffer();
		if (boole) {
			sb.append("{");
			sb.append("\"filename\":\"" + filename + "\",");
			sb.append("\"uuid\":\"" + uuid + "\"");
			sb.append("}");
			JSONObject result = JSONObject.parseObject(sb.toString()); 
			String data = result.toJSONString();
			return data;
		} else {
			sb.append("{");
			sb.append("\"filename\":\"上传失败\",");
			sb.append("\"uuid\":\"" + uuid + "\"");
			sb.append("}");
			JSONObject result = JSONObject.parseObject(sb.toString()); 
			String data = result.toJSONString();
			return data;
		}

	}
	

	@RequestMapping(value = "/upload")
	@ResponseBody
	private Object toFilesave(MultipartFile file, ModelMap map) {
		String uuid = UUID.randomUUID().toString();
		boolean boole = fileservice.savefilekj(file, uuid, "");
		String filename = file.getOriginalFilename()+","+uuid;
		if (boole) {
			return new AjaxResult(true, filename);
		} else {
			return new AjaxResult(true, file.getOriginalFilename());
		}

	}
	
	@Override
	public Object save(SysFileForm form) {
		try {
			SysFile sysFile = fileservice.findByUuid(form.getUuid());
			sysFile.setResourceprofile(form.getResourceprofile());
			System.out.println(form.getTbCurriculumid());
			sysFile.setTbCurriculum(tbCurriculumService.findById(form.getTbCurriculumid()));
			sysFile.setIsUsed(true);
			sysFile.setFiletypename("课件资源");
			fileservice.save(sysFile);
			return new AjaxResult(true,"数据保存成功");
		} catch (Exception e) {
			return new AjaxResult(false,"数据保存失败");
		}
	}

	/**
	 * 课件查询
	 */
	@Override
	public Specification<SysFile> buildSpec(SysFileForm form) {
		Specification<SysFile> specification = new Specification<SysFile>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<SysFile> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				Predicate name = cb.like(root.get("filetypename"), "%课件资源%");
				rules.add(name);
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
}
